/*
 * 文件名： CheckOrderAlipayScanPayCmbcImpl.java
 * 
 * 工程名称: checkorder-service
 *
 * Gopay
 *
 * 创建日期： 2017年1月20日
 *
 * Copyright(C) 2017, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.checkorder.service.impl.scan;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ScanPayBaseMessage;
import com.gopay.common.domain.bank.alipay.cmbc.AlipayTransMsg;
import com.gopay.common.domain.bank.alipay.cmbc.scan.AlipayQueryBody;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.ScanPayInteractRemoteService;

/**
 * 支付宝扫码支付结果查询
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2017年1月20日
 */
public class CheckOrderAlipayScanPayCmbcImpl implements BankOrderService {

	/**
	 * 定义日志对象
	 */
	private final static Logger logger = LoggerFactory.getLogger("ALIPAY-SCAN-CMBC");

	@Resource(name = "wechatScanClient")
	private ScanPayInteractRemoteService alipayScanClient;

	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		/**
		 * 对单返回对象
		 */
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());

		ScanPayBaseMessage message = new ScanPayBaseMessage();

		message.setOrderId(bankOrder.getOrderId()); // 国付宝系统订单号
		message.setBankOrderId(bankOrder.getOutOrderId());// 上送银行单号
		// message.setBank(BankConstants.BANK_LOGO_ALIPAY);// 支付宝
		message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));// 银行通道码
		message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));// 银行业务产品码
		message.setBank(bankOrder.getBankCode());

		Result result = new Result();
		try {
			if (BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())) {
				/**
				 * 退款交易请求退款查询接口 add by 宣广海 20161013
				 */
				message.setTkOriBankOrderId(bankOrder.getOriOutOrderId());// 原订单号
				result = alipayScanClient.refundQuery(message);
				return refundCheckOrder(result, bankOrder);
			} else {
				result = alipayScanClient.orderQuery(message);
			}
			if (result == null || !result.isSuccess()) {
				logger.error("alipayScanClient fail.");
				if (result == null || ProcCodeConstants.PROC_CODE_100F1002.equals(result.getResultCode())
						|| ProcCodeConstants.PROC_CODE_100E7027.equals(result.getResultCode())
						|| ProcCodeConstants.PROC_CODE_100E6063.equals(result.getResultCode())) {
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				}
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}

			@SuppressWarnings("unchecked")
			AlipayTransMsg<AlipayQueryBody> res = (AlipayTransMsg<AlipayQueryBody>) result.getDefaultModel();
			if (res == null) {
				/**
				 * 查询结果为空
				 */
				logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:"
						+ ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("返回对账结果为空");
				return checkOrderResult;
			}
			AlipayQueryBody queryResult = res.getBody();
			/**
			 * 状态为S表示通讯成功
			 */
			if (StringUtils.equals("000000", res.getHead().getRespCode())
					&& StringUtils.equals("S", res.getHead().getRespType())) {
				/**
				 * 原交易应答类型
				 */
				if (StringUtils.equals("S", queryResult.getOriRespType())
						&& StringUtils.equals("000000", queryResult.getOriRespCode())) {

					checkOrderResult.setSuccess(true);

					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());
					accInfo.setAmount(res.getAmount());
					accInfo.setRetCode("00");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);
					logger.error(
							"支付宝扫码支付订单：" + bankOrder.getOrderId() + "，交易成功" + "返回码：" + queryResult.getOriRespCode());
				} else if (StringUtils.equals("E", queryResult.getOriRespType())) {
					checkOrderResult.setBankFailure(true);
					checkOrderResult.setErrMsg("支付宝扫码交易返回交易失败！");
					logger.error("支付宝扫码支付订单：" + bankOrder.getOrderId() + "，交易失败" + "返回码：" + queryResult.getOriRespCode()
							+ "。返回信息为：" + queryResult.getOriRespMsg());
				} else if (StringUtils.equals("R", queryResult.getOriRespType())) {
					checkOrderResult.setErrMsg("支付宝扫码订单进行中！");
					logger.error("支付宝扫码支付订单：" + bankOrder.getOrderId() + "，交易处理中" + "返回码："
							+ queryResult.getOriRespCode() + "。返回信息为：" + queryResult.getOriRespMsg());
				} else {
					checkOrderResult.setErrMsg("支付宝扫码返回交易状态不明");
					logger.error("支付宝扫码支付订单：" + bankOrder.getOrderId() + "，返回交易状态不明，系统暂不处理" + "返回码："
							+ queryResult.getOriRespCode() + "。返回信息为：" + queryResult.getOriRespMsg());
				}
			} else {
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				logger.error("支付订单：" + bankOrder.getOrderId() + "，查询失败" + "err_code：" + res.getHead().getRespCode()
						+ "。错误信息为：" + res.getHead().getRespMsg());
			}
			return checkOrderResult;
		} catch (Exception e) {
			logger.error("wechatScanClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("支付宝扫码对账异常");
			return checkOrderResult;
		}

	}

	/**
	 * 
	 * 功能描述：退款查询订单处理
	 *
	 * @param result
	 * @param bankOrder
	 * @return
	 * 
	 * @author 宣广海
	 *
	 * @since 2017年1月22日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public CheckOrderResult refundCheckOrder(Result result, BankOrder bankOrder) {

		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		if (result == null || !result.isSuccess()) {
			logger.error("refund bankClient fail.");
			if (result == null || ProcCodeConstants.PROC_CODE_100F1002.equals(result.getResultCode())
					|| ProcCodeConstants.PROC_CODE_100E7027.equals(result.getResultCode())
					|| ProcCodeConstants.PROC_CODE_100E6063.equals(result.getResultCode())) {
				BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				checkOrderResult.setCommunicateError(true);
			}
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6062);
			checkOrderResult.setErrMsg("系统返回对账结果为空");
			return checkOrderResult;
		}
		AlipayTransMsg<AlipayQueryBody> res = (AlipayTransMsg<AlipayQueryBody>) result.getDefaultModel();
		if (res == null) {
			// 查询订单为空
			logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062
					+ " err:bis query is null.");
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("银行返回对账结果为空");
			return checkOrderResult;
		}
		/**
		 * 状态为S表示通讯成功
		 */
		if (StringUtils.equals("000000", res.getHead().getRespCode())
				&& StringUtils.equals("S", res.getHead().getRespType())) {
			/**
			 * 原交易应答类型
			 */
			if (StringUtils.equals("000000", res.getBody().getOriRespCode())
					&& StringUtils.equals("S", res.getBody().getOriRespType())) {
				// 成功处理
				checkOrderResult.setSuccess(true);
				InAccInfo accInfo = new InAccInfo();
				accInfo.setOrderId(bankOrder.getOrderId());
				accInfo.setAmount(res.getAmount());// 退款金额
				accInfo.setRetCode("00");
				accInfo.setCardType(BankCardType.Unknown.toString());
				checkOrderResult.setAccInfo(accInfo);
				logger.error("支付宝扫码支付refund订单：" + bankOrder.getOrderId() + "的交易银行处理成功。" + "返回码："
						+ res.getBody().getOriRespCode());
			} else if (StringUtils.equals("E", res.getBody().getOriRespType())) {
				/**
				 * 退款记录不存在200108
				 */
				if ("200001".equals(res.getBody().getOriRespCode())) {
					logger.error("支付宝扫码支付refund订单：" + bankOrder.getOrderId() + "的退款交易不存在" + "返回码："
							+ res.getBody().getOriRespCode() + "，返回信息为：" + res.getBody().getOriRespMsg());
					String errMsg = res.getBody().getOriRespMsg();
					if (errMsg != null) {
						checkOrderResult.setErrMsg(errMsg);
					} else {
						checkOrderResult.setErrMsg("银行返回退款交易不存在。");
					}
					// 查询订单不存在
					checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
				}
				if ("200003".equals(res.getBody().getOriRespCode())) {

					// 失败处理
					checkOrderResult.setBankFailure(true);
					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());
					accInfo.setAmount(res.getAmount());
					accInfo.setRetCode("01");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);
					logger.error("支付宝扫码支付refund订单：" + bankOrder.getOrderId() + "的交易退款失败。" + "返回码："
							+ res.getBody().getOriRespCode() + "，返回信息为：" + res.getBody().getOriRespMsg());
					String errMsg = res.getBody().getOriRespMsg();
					if (errMsg != null) {
						checkOrderResult.setErrMsg(errMsg);
					} else {
						checkOrderResult.setErrMsg("银行返回退款交易失败。");
					}
				}
			} else if (StringUtils.equals("R", res.getBody().getOriRespType())) {				
				logger.error("支付宝扫码支付refund订单：" + bankOrder.getOrderId() + "的退款交易进行中" + "返回码："
						+ res.getBody().getOriRespCode() + "，返回信息为：" + res.getBody().getOriRespMsg());
				String errMsg = res.getBody().getOriRespMsg();
				if (errMsg != null) {
					checkOrderResult.setErrMsg(errMsg);
				} else {
					checkOrderResult.setErrMsg("银行返回退款交易处理中.");
				}
				if ("200001".equals(res.getBody().getOriRespCode())) {
					logger.error("支付宝扫码支付refund订单：" + bankOrder.getOrderId() + "的退款交易不存在" + "返回码："
							+ res.getBody().getOriRespCode() + "，返回信息为：" + res.getBody().getOriRespMsg());
					errMsg = res.getBody().getOriRespMsg();
					if (errMsg != null) {
						checkOrderResult.setErrMsg(errMsg);
					} else {
						checkOrderResult.setErrMsg("银行返回退款交易不存在。");
					}
					// 查询订单不存在
					checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
				}
			}
		} else {
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("系统返回对账结果为空");
			if(bankOrder.getOrderStatus().equals(BankOrderStatus.ACCEPTED)){
				checkOrderResult.setErrMsg("系统返回对账结果为空,订单已受理，请耐心等待");
			}
			logger.error("支付退款订单：" + bankOrder.getOrderId() + "，查询失败" + "err_code：" + res.getHead().getRespCode()
					+ "。返回信息为：" + res.getHead().getRespMsg());

		}
		return checkOrderResult;
	}

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
